<?php
/**
* feed_user token 模型
*
* @author hejigui <hejigui@soften.cn>
*/

class System_token_model extends CI_Model{

    private $_tokens_key = 'system_token';
    private $_write_db;
	/**
	* __construct
	*
	* @access public
	* @return string $mixed
	*/
	public function __construct() {
		parent::__construct();
		$this->load->database();
        $this->load->library('error_code_library');
        $this->_write_db = $this->load->database('master', TRUE);
        $this->load->driver('cache', array('adapter' => 'redis'));
	}

	/**
	* 获取当前(小时内)使用次数最少的token信息
	* 若无可用token,情况如下:
	*         1 token有效超时--自动登录
	* 		  2 使用次数都超标--检查是否有新appkey,有则自动登录,一帐号在多个appkey下的自动登录.
	* @access public
	* @param array $map xxxxxx [Must]
	* @return string $mixed
	*/
	public function get_system_token() {
        $tokens = $this->cache->get($this->_tokens_key);
        if(FALSE == $tokens) {
            $tokens = $this->get_system_token_from_db();
            if(is_array($tokens) && array_key_exists('error', $tokens)) {
                return $tokens;
            } else {
                $this->cache->save($this->_tokens_key, json_encode($tokens),  $this->config->item('system_token_life'));
                return $tokens;
            }
        } else {
            return json_decode($tokens, true);
        }
	}

    public function get_system_token_from_db() {
        $this->db->select('access_token');
        $this->db->from('system_token');
        $this->db->where('status', 1);
        $query = $this->db->get();

        if($query->num_rows() > 0) {
            $result_array = $query->result_array();
            $tokens = array();
            foreach($result_array as $token_info) {
                $tokens[] = $token_info['access_token'];
            }
            return $tokens;
        } else {
            return $this->error_code_library->getError('system', 'data', 'no_data', 'In Function '. __FUNCTION__);
        }
    }

    public function update_system_token() {
        $tokens = $this->get_system_token_from_db();
        if(is_array($tokens) && array_key_exists('error', $tokens)) {
            return $tokens;
        } else {
            $this->cache->delete($this->_tokens_key);
            $this->cache->save($this->_tokens_key, json_encode($tokens),  $this->config->item('system_token_life'));
            return $tokens;
        }
    }
}

?>